package cn.neusoft.interceptor;

import cn.neusoft.exception.AppException;
import cn.neusoft.exception.AppExceptionCodeMsg;
import cn.neusoft.util.JwtUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //给所有的OPTIONS请求放行
        String method = request.getMethod();
        if ("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }

        //获取token
        String token = request.getHeader("token");
        System.out.println("--------登录拦截------"+token);

        if (StringUtils.isEmpty(token)){
            throw new AppException(AppExceptionCodeMsg.NO_LOGIN);
        }

        //解析token
        Claims claimsVyToken = JwtUtils.getClaimsVyToken(token);
        Object username = claimsVyToken.get("username");
        System.out.println("获取到username--------"+username);

        if (username==null){
            throw new AppException(AppExceptionCodeMsg.NO_LOGIN);
        }

        return true;
    }
}
